﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.Data;
using System.Data.Entity;
using System.Text;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using System.Data.Entity.Infrastructure;
using CdmDeviceHealthMvc.Models;
using SnShared.Models;

namespace CdmDeviceHealthMvc.Controllers
{
    public class StatusController : Controller
    {
        private CdmDataCtx db = CdmDataCtx.CreateDbContext();
        public ActionResult Index()
        {
            ViewBag.Title = "Continuous Diagnostics and Mitigation";
            return View();
        }
        
        public ActionResult EditingInline_Read([DataSourceRequest] DataSourceRequest request)
        {
            List<Computer> computerList = db.Computers.ToList();
            List<StatusItem> statusList = new List<StatusItem>();
            foreach (SoftwarePackage package in db.SoftwarePackages.ToList())
            { 
                if (package.Revoked)
                    continue;

                StatusItem newStatusItem = new StatusItem();                
                newStatusItem.SoftwarePackageId = package.Id;
                newStatusItem.SoftwarePackageName = package.Name;
                
                StringBuilder sb = new StringBuilder();

                foreach (Computer c in package.Computers)                
                    sb.AppendFormat("{0} <br/>", c.Name);

                newStatusItem.ComputerName = sb.ToString();

                StringBuilder sb2 = new StringBuilder();

                foreach (InstalledFile f in package.Files)
                    sb2.AppendFormat(";{0}; ", f.Name);

                newStatusItem.FileName = sb2.ToString();

                statusList.Add(newStatusItem);
            }
            DataSourceResult myResult = statusList.ToDataSourceResult(request);
            return Json(myResult, JsonRequestBehavior.AllowGet);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditingInline_Update([DataSourceRequest] DataSourceRequest request, int SoftwarePackageId)
        {
            if (ModelState.IsValid)
            {
                SoftwarePackage package = db.SoftwarePackages.Single(c => c.Id.Equals(SoftwarePackageId));
                if (package != null)
                {
                    package.Revoked = true;
                    db.Entry(package).State = EntityState.Modified;          
                }
            }
            db.SaveChanges();
            return Json(ModelState.ToDataSourceResult());
        }
    }
}